// import myStore from "/stores/my.ts"
export default class {
	// https://nntzback.jyhdkj.com/system/testacc/release/list/type?info_type=2
	baseUrl: string = "https://nntzback.jyhdkj.com"
	url: string
	header: object | undefined
	data: string | object | ArrayBuffer
	// 直接使用字面量
	method: "GET" | "POST" | "PUT" | "DELETE" | "CONNECT" | "HEAD" | "OPTIONS" | "TRACE"

	public beforeRequest() {
		// 如果请求的路径中存在了/my/，则说明需要用户登录后，拿到token值才可以发生请求的
		if (this.url.indexOf("/my/") !== -1) {
			this.header = {
				// authoriztion: myStore().token
				authoriztion: ""
			}
		}
		uni.showLoading({
			title: "数据加载中..."
		})
	}
	public afterRequest() {
		uni.hideLoading()
	}
	constructor({ url = "", header = {} } = {}) {
		this.baseUrl += url
		this.header = header
	}
	// 获取
	get({ url = "", data = {} } = {}) {
		this.method = "GET"
		this.url = `${this.baseUrl}${url}`
		this.data = data
		return this.handle()
	}
	// 添加、创建
	post(url = "", data = {}) {
		this.method = "POST"
		this.url = `${this.baseUrl}${url}`
		this.data = data
		return this.handle()
	}
	// 替换资源(完整资源)
	put(url = "", data = {}) {
		this.method = "PUT"
		this.url = `${this.baseUrl}${url}`
		// 将请求的内容设置为json字符串
		this.data = JSON.stringify(data)
		return this.handle()
	}
	// 删除
	delete(url = "", data = {}) {
		this.method = "DELETE"
		this.url = `${this.baseUrl}${url}`
		this.data = data
		return this.handle()
	}
	private handle({ url, method, data, header } = this) {
		// 请求之前做一些事
		this.beforeRequest()
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				method,
				data,
				header,
				success: res => resolve(res),
				fail: err => reject(err),
				complete: () => {
					// 请求完成以后做一些事情
					this.afterRequest()
				}
			})
		})
	}
}